package com.aipartner.service.impl;

import com.aipartner.dto.UploadExampleRequest;
import com.aipartner.entity.AiImageExample;
import com.aipartner.entity.AiImageExampleLike;
import com.aipartner.entity.UserUploadRecord;
import com.aipartner.mapper.AiImageExampleMapper;
import com.aipartner.mapper.AiImageExampleLikeMapper;
import com.aipartner.mapper.UserUploadRecordMapper;
import com.aipartner.service.UserUploadService;
import com.aipartner.websocket.AiImageWebSocketServer;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.time.LocalDateTime;
import java.util.UUID;

/**
 * 用户上传服务实现
 */
@Service
@Slf4j
public class UserUploadServiceImpl implements UserUploadService {

    @Autowired
    private UserUploadRecordMapper uploadRecordMapper;
    
    @Autowired
    private AiImageExampleMapper exampleMapper;
    
    
    @Autowired
    private AiImageExampleLikeMapper likeMapper;
    
    @Value("${file.upload.path:./uploads/}")
    private String uploadPath;
    
    @Value("${file.upload.url-prefix:/uploads/}")
    private String urlPrefix;

    @Override
    @Transactional
    public Long uploadExampleByUrl(UploadExampleRequest request) {
        log.info("开始处理用户作品上传: userId={}, title={}, imageUrl={}", 
                request.getUserId(), request.getTitle(), request.getImageUrl());
        
        String originalImageUrl = request.getImageUrl();
        String finalImageUrl = originalImageUrl;
        
        // 首先检查URL是否为空或无效
        if (originalImageUrl == null || originalImageUrl.trim().isEmpty() || 
            originalImageUrl.equals("undefined") || originalImageUrl.equals("null")) {
            log.warn("接收到无效的图片URL: [{}]，直接标记为INVALID_URL", originalImageUrl);
            finalImageUrl = "INVALID_URL";
        } else {
            // 详细记录URL判断过程
            boolean needDownload = shouldDownloadImage(originalImageUrl);
            log.info("URL下载判断结果: needDownload={}, imageUrl=[{}]", needDownload, originalImageUrl);
            
            // 检查是否是微信临时文件或需要下载的URL
            if (needDownload) {
                try {
                    log.info("检测到需要下载的图片URL，开始下载: {}", originalImageUrl);
                    finalImageUrl = downloadAndSaveImage(originalImageUrl, request.getUserId());
                    log.info("图片下载成功，本地路径: {}", finalImageUrl);
                } catch (Exception e) {
                    log.error("下载图片失败: originalUrl={}, error={}", originalImageUrl, e.getMessage(), e);
                    // 如果下载失败，仍然保存原URL，但标记为无效
                    finalImageUrl = "INVALID_URL";
                    log.warn("图片下载失败，标记为无效URL: userId={}, originalUrl={}", 
                            request.getUserId(), originalImageUrl);
                }
            } else {
                log.info("URL无需下载，直接使用: {}", originalImageUrl);
            }
        }
        
        // 直接保存到ai_image_examples表，实现统一管理
        AiImageExample example = new AiImageExample();
        example.setTitle(request.getTitle());
        example.setImageUrl(finalImageUrl);
        example.setPrompt(request.getPrompt());
        example.setStyle(request.getStyle() != null ? request.getStyle() : "用户创作");
        example.setSize(request.getSize() != null ? request.getSize() : "1024x1024");
        example.setSortOrder(999); // 用户作品排在系统示例后面
        example.setStatus(1); // 启用
        example.setUserId(request.getUserId()); // 关键：设置用户ID区分用户作品
        example.setUploadTime(LocalDateTime.now());
        example.setReviewStatus(1); // 默认审核通过
        example.setLikeCount(0);
        example.setViewCount(0);
        example.setIsFeatured(0); // 不推荐
        example.setCreateTime(LocalDateTime.now());
        example.setUpdateTime(LocalDateTime.now());
        
        exampleMapper.insert(example);
        log.info("用户作品已保存到ai_image_examples表: userId={}, exampleId={}, title={}, finalImageUrl={}", 
                request.getUserId(), example.getId(), example.getTitle(), finalImageUrl);
        
        // 同时创建上传记录用于统计
        UserUploadRecord record = new UserUploadRecord();
        record.setUserId(request.getUserId());
        record.setOriginalFilename("ai_generated_image.jpg");
        record.setFilePath(request.getImageUrl());
        record.setFileSize(0);
        record.setTitle(request.getTitle());
        record.setPrompt(request.getPrompt());
        record.setStyle(request.getStyle());
        record.setSize(request.getSize());
        record.setReviewStatus(1); // 已通过审核
        record.setUploadTime(LocalDateTime.now());
        record.setExampleId(example.getId()); // 关联ai_image_examples的ID
        
        uploadRecordMapper.insert(record);
        
        // 通过WebSocket广播新作品
        try {
            AiImageWebSocketServer.broadcastNewExample(example);
            log.info("广播新作品成功: exampleId={}", example.getId());
        } catch (Exception e) {
            log.error("广播新作品失败: exampleId={}", example.getId(), e);
        }
        
        return example.getId(); // 返回示例ID
    }

    @Override
    @Transactional
    public Long uploadExample(MultipartFile file, UploadExampleRequest request) {
        try {
            // 获取项目根目录并创建上传目录
            String projectRoot = System.getProperty("user.dir");
            File uploadDir = new File(projectRoot, "uploads/user-examples");
            if (!uploadDir.exists()) {
                uploadDir.mkdirs();
            }
            
            log.info("文件上传目录: {}", uploadDir.getAbsolutePath());
            
            // 生成唯一文件名
            String originalFilename = file.getOriginalFilename();
            String extension = "";
            if (originalFilename != null && originalFilename.contains(".")) {
                extension = originalFilename.substring(originalFilename.lastIndexOf("."));
            }
            String newFileName = UUID.randomUUID().toString() + extension;
            
            // 保存文件
            File targetFile = new File(uploadDir, newFileName);
            file.transferTo(targetFile);
            
            // 构造访问URL - urlPrefix 已经包含了完整路径
            String fileUrl = urlPrefix + newFileName;
            
            // 直接保存到ai_image_examples表，实现统一管理
            AiImageExample example = new AiImageExample();
            example.setTitle(request.getTitle());
            example.setImageUrl(fileUrl);
            example.setPrompt(request.getPrompt());
            example.setStyle(request.getStyle() != null ? request.getStyle() : "用户创作");
            example.setSize(request.getSize() != null ? request.getSize() : "1024x1024");
            example.setSortOrder(999); // 用户作品排在系统示例后面
            example.setStatus(1); // 启用
            example.setUserId(request.getUserId()); // 关键：设置用户ID区分用户作品
            example.setUploadTime(LocalDateTime.now());
            example.setReviewStatus(1); // 默认审核通过，文件上传类型可以设为待审核
            example.setLikeCount(0);
            example.setViewCount(0);
            example.setIsFeatured(0); // 不推荐
            example.setOriginalFilename(originalFilename);
            example.setFileSize((int) file.getSize());
            example.setCreateTime(LocalDateTime.now());
            example.setUpdateTime(LocalDateTime.now());
            
            exampleMapper.insert(example);
            log.info("用户文件上传作品已保存到ai_image_examples表: userId={}, exampleId={}, filename={}", 
                    request.getUserId(), example.getId(), newFileName);
            
            // 创建上传记录用于统计
            UserUploadRecord record = new UserUploadRecord();
            record.setUserId(request.getUserId());
            record.setOriginalFilename(originalFilename);
            record.setFilePath(fileUrl);
            record.setFileSize((int) file.getSize());
            record.setTitle(request.getTitle());
            record.setPrompt(request.getPrompt());
            record.setStyle(request.getStyle());
            record.setSize(request.getSize());
            record.setReviewStatus(1); // 已通过审核
            record.setUploadTime(LocalDateTime.now());
            record.setExampleId(example.getId()); // 关联ai_image_examples的ID
            
            uploadRecordMapper.insert(record);
            
            // 通过WebSocket广播新作品
            try {
                AiImageWebSocketServer.broadcastNewExample(example);
                log.info("广播新上传作品成功: exampleId={}", example.getId());
            } catch (Exception e) {
                log.error("广播新上传作品失败: exampleId={}", example.getId(), e);
            }
            
            return example.getId();
            
        } catch (IOException e) {
            throw new RuntimeException("文件保存失败: " + e.getMessage(), e);
        }
    }

    @Override
    public Page<?> getUserUploadRecords(Long userId, Integer current, Integer size) {
        Page<UserUploadRecord> page = new Page<>(current, size);
        QueryWrapper<UserUploadRecord> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId);
        wrapper.orderByDesc("upload_time");
        
        return uploadRecordMapper.selectPage(page, wrapper);
    }

    @Override
    @Transactional
    public boolean deleteUploadRecord(Long recordId, Long userId) {
        QueryWrapper<UserUploadRecord> wrapper = new QueryWrapper<>();
        wrapper.eq("id", recordId);
        wrapper.eq("user_id", userId);
        
        UserUploadRecord record = uploadRecordMapper.selectOne(wrapper);
        if (record == null) {
            return false;
        }
        
        // 删除文件
        try {
            String filePath = record.getFilePath();
            if (filePath.startsWith(urlPrefix)) {
                String fileName = filePath.substring(urlPrefix.length());
                String projectRoot = System.getProperty("user.dir");
                File file = new File(projectRoot, "uploads/user-examples/" + fileName);
                if (file.exists()) {
                    file.delete();
                    log.info("删除文件成功: {}", file.getAbsolutePath());
                } else {
                    log.warn("文件不存在: {}", file.getAbsolutePath());
                }
            }
        } catch (Exception e) {
            log.warn("删除文件失败: {}", e.getMessage());
        }
        
        // 删除数据库记录
        return uploadRecordMapper.deleteById(recordId) > 0;
    }

    @Override
    @Transactional
    public boolean toggleLike(Long exampleId, Long userId) {
        QueryWrapper<AiImageExampleLike> wrapper = new QueryWrapper<>();
        wrapper.eq("example_id", exampleId);
        wrapper.eq("user_id", userId);
        
        AiImageExampleLike existingLike = likeMapper.selectOne(wrapper);
        
        if (existingLike != null) {
            // 取消点赞
            likeMapper.deleteById(existingLike.getId());
            
            // 减少点赞数
            AiImageExample example = exampleMapper.selectById(exampleId);
            if (example != null && example.getLikeCount() > 0) {
                example.setLikeCount(example.getLikeCount() - 1);
                exampleMapper.updateById(example);
            }
            
            return false;
        } else {
            // 添加点赞
            AiImageExampleLike like = new AiImageExampleLike();
            like.setExampleId(exampleId);
            like.setUserId(userId);
            like.setCreateTime(LocalDateTime.now());
            likeMapper.insert(like);
            
            // 增加点赞数
            AiImageExample example = exampleMapper.selectById(exampleId);
            if (example != null) {
                example.setLikeCount(example.getLikeCount() + 1);
                exampleMapper.updateById(example);
            }
            
            return true;
        }
    }
    
    /**
     * 判断是否需要下载图片
     * @param imageUrl 图片URL
     * @return true如果需要下载
     */
    private boolean shouldDownloadImage(String imageUrl) {
        if (imageUrl == null || imageUrl.trim().isEmpty()) {
            log.warn("URL为空，无需下载: [{}]", imageUrl);
            return false;
        }
        
        String trimmedUrl = imageUrl.trim();
        log.info("判断URL是否需要下载: [{}]", trimmedUrl);
        
        // 已经是我们服务器的URL，无需下载
        if (trimmedUrl.startsWith("/uploads/")) {
            log.info("URL已是本地路径，无需下载: [{}]", trimmedUrl);
            return false;
        }
        
        // 已经是完整的HTTP/HTTPS URL且指向我们的服务器，无需下载
        if ((trimmedUrl.startsWith("http://") || trimmedUrl.startsWith("https://")) && 
            (trimmedUrl.contains("192.168.100.102:8080") || trimmedUrl.contains("localhost"))) {
            log.info("URL已是完整的本地服务器URL，无需下载: [{}]", trimmedUrl);
            return false;
        }
        
        // 检查是否是微信临时文件或其他需要下载的格式
        boolean needDownload = trimmedUrl.startsWith("wxfile://") || 
                              trimmedUrl.startsWith("http://tmp/") || 
                              trimmedUrl.startsWith("https://tmp/") ||
                              trimmedUrl.contains("/tmp/") ||
                              trimmedUrl.contains("//tmp") ||
                              trimmedUrl.startsWith("http://usr/") ||
                              trimmedUrl.startsWith("file://") ||
                              // 微信小程序临时文件的其他格式
                              trimmedUrl.contains("wxfile") ||
                              // 如果是HTTP/HTTPS但不是我们的服务器，也需要下载
                              (trimmedUrl.startsWith("http://") || trimmedUrl.startsWith("https://"));
        
        log.info("URL下载判断结果: needDownload={}, reason={}", needDownload, 
                needDownload ? "检测到需要下载的URL格式" : "URL格式无需下载");
        
        return needDownload;
    }
    
    /**
     * 下载并保存图片到本地
     * @param imageUrl 原始图片URL
     * @param userId 用户ID
     * @return 本地文件的访问路径
     * @throws IOException 下载失败时抛出异常
     */
    private String downloadAndSaveImage(String imageUrl, Long userId) throws IOException {
        // 获取项目根目录并创建用户作品上传目录
        String projectRoot = System.getProperty("user.dir");
        File uploadDir = new File(projectRoot, "uploads/user-works");
        if (!uploadDir.exists()) {
            uploadDir.mkdirs();
        }
        
        // 生成唯一文件名
        String fileExtension = ".jpg"; // 默认jpg格式
        String newFileName = "user_" + userId + "_" + System.currentTimeMillis() + fileExtension;
        File targetFile = new File(uploadDir, newFileName);
        
        // 如果是微信小程序的wxfile://格式，需要特殊处理
        if (imageUrl.startsWith("wxfile://")) {
            // 微信小程序的临时文件路径无法直接下载，标记为无效
            log.warn("检测到微信小程序临时文件路径，无法下载: {}", imageUrl);
            throw new IOException("微信小程序临时文件无法下载: " + imageUrl);
        }
        
        // 尝试下载图片
        try {
            log.info("开始下载图片: {} -> {}", imageUrl, targetFile.getAbsolutePath());
            
            URL url = new URL(imageUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.setConnectTimeout(10000); // 10秒连接超时
            connection.setReadTimeout(30000);    // 30秒读取超时
            connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36");
            
            int responseCode = connection.getResponseCode();
            if (responseCode != HttpURLConnection.HTTP_OK) {
                throw new IOException("HTTP请求失败，状态码: " + responseCode);
            }
            
            // 检查Content-Type是否为图片
            String contentType = connection.getContentType();
            if (contentType != null && !contentType.startsWith("image/")) {
                log.warn("URL返回的不是图片类型: {}, Content-Type: {}", imageUrl, contentType);
            }
            
            // 下载文件
            try (InputStream inputStream = connection.getInputStream();
                 FileOutputStream outputStream = new FileOutputStream(targetFile)) {
                
                byte[] buffer = new byte[1024];
                int bytesRead;
                long totalBytesRead = 0;
                
                while ((bytesRead = inputStream.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, bytesRead);
                    totalBytesRead += bytesRead;
                }
                
                log.info("图片下载完成: 文件大小={}字节, 保存路径={}", totalBytesRead, targetFile.getAbsolutePath());
            }
            
            // 返回访问路径
            String relativePath = "/uploads/user-works/" + newFileName;
            log.info("生成图片访问路径: {}", relativePath);
            return relativePath;
            
        } catch (Exception e) {
            // 清理可能创建的文件
            if (targetFile.exists()) {
                targetFile.delete();
            }
            throw new IOException("下载图片失败: " + e.getMessage(), e);
        }
    }
}
